package com.catering.service.impl;

import com.catering.mapper.DOrderinformationMapper;
import com.catering.mapper.InventoryMapper;
import com.catering.pojo.DOrderinformation;
import com.catering.service.DOrderinformationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DOrderinformationServiceImpl implements DOrderinformationService {
    @Resource
    private DOrderinformationMapper dOrderinformationMapper;

    @Resource
    private InventoryMapper inventoryMapper;

    @Override
    public List<DOrderinformation> list() {
        List<DOrderinformation> list=dOrderinformationMapper.findAll();
        return list;
    }

    @Override
    public List<DOrderinformation> take() {
        List<DOrderinformation> list=dOrderinformationMapper.take();
        return list;
    }

    /**
     * 批量添加订单项信息
     *
     * @param orderItems 订单项集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addBatchOrderItems(List<DOrderinformation> orderItems) {
        Map<String, Object> result = new HashMap<>();

        if (orderItems == null || orderItems.isEmpty()) {
            result.put("code", 500);
            result.put("msg", "订单项不能为空");
            return result;
        }

        // 为每个订单项设置创建时间和默认值
        for (DOrderinformation item : orderItems) {
            if (item.getCreate_time() == null) {
                item.setCreate_time(new Date());
            }
            // 初始状态设为0（待处理）
            if (item.getStatus() == null) {
                item.setStatus(0);
            }
            // 设置默认用户ID为1
            if (item.getUid() == null) {
                item.setUid(1);
            }
        }

        try {
            // 执行批量插入
            int rows = dOrderinformationMapper.insertBatchOrderItems(orderItems);
            //菜品是循环进行添加的,根据菜品的名称，减少库存
            for (DOrderinformation item : orderItems) {
                inventoryMapper.reduceInventory(item.getDishname());
            }

            result.put("code", 200);
            result.put("msg", "添加成功");
            result.put("data", rows);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "添加订单项失败: " + e.getMessage());
            return result;
        }
    }
}
